<?php
class Db {
    private $host;
    private $username;
    private $password;
    private $database;
    private $charset;
    private $pdo;

    public function __construct() {
        $config = require __DIR__ . '/../config/config.php';

        $this->host = $config['host'];
        $this->username = $config['username'];
        $this->password = $config['password'];
        $this->database = $config['database'];
        $this->charset = $config['charset'];
        $this->connect();
    }

    private function connect() {
        try {
            $dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->charset}";
            $this->pdo = new PDO($dsn, $this->username, $this->password);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }
    }

    public function query($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
    
    public function insert($table, $data) {
        $columns = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));
        $sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($data);
        return $this->pdo->lastInsertId();
    }

    public function update($table, $data, $conditions) {
        $set = [];
        $params = []; // 用于存储绑定参数

        foreach ($data as $key => $value) {
            if ($value === 'NOW()') {
                $set[] = "$key = NOW()"; // 直接使用 NOW()
            } else {
                $set[] = "$key = :$key";
                $params[":$key"] = $value; // 仅将非 NOW() 的值添加到参数中
            }
        }
        $set = implode(', ', $set);

        $where = [];
        foreach ($conditions as $key => $value) {
            $where[] = "$key = :$key";
            $params[":$key"] = $value; // 将条件参数添加到参数中
        }
        $where = implode(' AND ', $where);

        $sql = "UPDATE {$table} SET {$set} WHERE {$where}";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params); // 只传递绑定参数
        return $stmt->rowCount();
    }

    public function delete($table, $conditions) {
        $where = [];
        foreach ($conditions as $key => $value) {
            $where[] = "$key = :$key";
        }
        $where = implode(' AND ', $where);

        $sql = "DELETE FROM {$table} WHERE {$where}";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($conditions);
        return $stmt->rowCount();
    }

    public function userExists($username) {
        $sql = "SELECT COUNT(*) as count FROM users WHERE username = :username";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['username' => $username]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['count'] > 0;
    }

    public function beginTransaction() {
        return $this->pdo->beginTransaction();
    }

    public function commit() {
        return $this->pdo->commit();
    }

    public function rollBack() {
        return $this->pdo->rollBack();
    }

    public function __destruct() {
        $this->pdo = null;
    }
}

// 查询
// $db = new Db();
// $results = $db->query("SELECT * FROM users");
// foreach ($results as $row) {
//     print_r($row);
// }

// 插入
// $db = new Db();
// $user_id = $db->insert('users', [
//     'username' => 'testuser',
//     'password' => password_hash('testpassword', PASSWORD_BCRYPT),
//     'registration_ip' => '127.0.0.1'
// ]);
// echo "插入的用户 ID: $user_id";

// 更新
// $db = new Db();
// $updated_rows = $db->update('users', ['password' => password_hash('newpassword', PASSWORD_BCRYPT)], ['id' => 1]);
// echo "更新的行数: $updated_rows";

// 删除
// $db = new Db();
// $deleted_rows = $db->delete('users', ['id' => 1]);
// echo "删除的行数: $deleted_rows";